import pandas as pd
import numpy as np
import os
import cv2
from dr_to_jpg import monochrome_convert,read_dcm_from_dir
from tqdm import tqdm
import json
import random
import scipy.ndimage as nd

Point_Name_Dict={
    "{'关键点名称': ['第1胸椎棘突']}":0,
    "{'关键点名称': ['第2胸椎棘突']}":1,
    "{'关键点名称': ['第3胸椎棘突']}":2,
    "{'关键点名称': ['第4胸椎棘突']}":3,
    "{'关键点名称': ['右侧第3肋骨外缘']}":4,
    "{'关键点名称': ['右侧第4肋骨外缘']}":5,
    "{'关键点名称': ['右侧第5肋骨外缘']}":6,
    "{'关键点名称': ['右侧第6肋骨外缘']}":7,
    "{'关键点名称': ['左侧第3肋骨外缘']}":8,
    "{'关键点名称': ['左侧第4肋骨外缘']}":9,
    "{'关键点名称': ['左侧第5肋骨外缘']}":10,
    "{'关键点名称': ['左侧第6肋骨外缘']}":11,
    "{'关键点名称': ['左侧锁骨内侧上缘']}":12,
    "{'关键点名称': ['左侧锁骨内侧下缘']}":13,
    "{'关键点名称': ['左侧锁骨外侧上缘']}":14,
    "{'关键点名称': ['左侧锁骨外侧下缘']}":15,
    "{'关键点名称': ['右侧锁骨内侧上缘']}":16,
    "{'关键点名称': ['右侧锁骨内侧下缘']}":17,
    "{'关键点名称': ['右侧锁骨外侧上缘']}":18,
    "{'关键点名称': ['右侧锁骨外侧下缘']}":19,
    "{'关键点名称': ['右侧肺尖']}":20,
    "{'关键点名称': ['左侧肺尖']}":21,
    "{'关键点名称': ['右侧肋膈角']}":22,
    "{'关键点名称': ['左侧肋膈角']}":23,
    "{'关键点名称': ['右侧心膈角']}":24,
    "{'关键点名称': ['左侧心膈角']}":25,
}


def conver_csv(csv_dir,save_json_dir):
    ## 将csv文件进行拆分。，分成三个任务（关键点，检测，关键的连接而成的mask区域）分开保存到json中。
    ## 并将dcm文件转换成jpg进行保存。
    box_dict = {}
    point_dict = {}
    rec_dict = {}
    csv_data = pd.read_csv(csv_dir)
    csv_data_point = csv_data[(csv_data['geometry'] == 'point')]
    csv_data_box = csv_data[(csv_data['geometry'] == 'rectangle')]
    csv_data_pol = csv_data[(csv_data['geometry'] == 'polygon')]
    ## 处理point
    last_name = csv_data_point.iloc[0].loc['StudyInstanceUID']
    ## 在list中先存入宽高spacing等信息
    point_dict[csv_data_point.iloc[0].loc['StudyInstanceUID']] = [(int(csv_data_point.iloc[0].loc['rows']),int(csv_data_point.iloc[0].loc['columns']),
                                                                   float(csv_data_point.iloc[0].loc['spacing'].split(',')[0].replace('[','').replace("'",'')))]
    for index in tqdm(range(len(csv_data_point))):
        if last_name != csv_data_point.iloc[index].loc['StudyInstanceUID']:
            ## 在list中先存入宽高spacing等信息
            point_dict[csv_data_point.iloc[index].loc['StudyInstanceUID']] = [(int(csv_data_point.iloc[index].loc['rows']),int(csv_data_point.iloc[index].loc['columns']),
                                                                   float(csv_data_point.iloc[index].loc['spacing'].split(',')[0].replace('[','')))]
        point = [int(csv_data_point.iloc[index].loc['points'].split(',')[0].replace('[[', '')),
                 int(csv_data_point.iloc[index].loc['points'].split(',')[1].replace(']]', '').replace(' ',''))]
        point_dict[csv_data_point.iloc[index].loc['StudyInstanceUID']].append([point,Point_Name_Dict[csv_data_point.iloc[index].loc['selected']]])
        last_name = csv_data_point.iloc[index].loc['StudyInstanceUID']
    json_list = []
    for k,value in point_dict.items():
        ## 先取出图像信息，存在value开头
        image_info = value[0]
        ## 剩下的均为点位信息，进行处理
        value = value[1:]
        # if os.path.exists(os.path.join(jpg_path,k+'.jpg')):
        for i in value:
            if i[0][0] < 0 or i[0][1] < 0:
                value.remove(i)
            ## 针对存在缺失值的数据 进行处理.
        value_name = [p[1] for p in value]
        true_name = [i for i in range(26)]
        miss_name = [p for p in true_name if p not in value_name]
        for j in miss_name:
            value.append([[0,0],j])
        json_list.append({
            'name':k,
            'info':image_info,
            'point':sorted(value,key=lambda j: j[1])
        })
    random.shuffle(json_list)
    print(len(json_list))
    with open(save_json_dir,'w') as f:
        json.dump(json_list,f)
    ## 按照3：7比例划分训练验证集
    # with open(save_json_dir.replace('.json','_train.json'),'w') as f:
    #     json.dump(json_list[:int(0.7*len(json_list))],f)
    # with open(save_json_dir.replace('.json','_val.json'),'w') as f:
    #     json.dump(json_list[int(0.7*len(json_list)):],f)


    # ## 处理box
    # last_name = csv_data_box.iloc[0].loc['sop']
    # box_dict[csv_data_box.iloc[0].loc['sop']] = []
    # for index in range(len(csv_data_box)):
    #     if last_name != csv_data_box.iloc[index].loc['sop']:
    #         point_dict[csv_data_box.iloc[index].loc['sop']] = []
    #     box = [int(csv_data_box.iloc[index].loc['points'].split(',')[0].replace('[[', '')),
    #              int(csv_data_box.iloc[index].loc['points'].split(',')[1].replace(']]', '').replace(' ', ''))]
    #     box_dict[csv_data_box.iloc[index].loc['sop']].append(
    #         [box, Point_Name_Dict[csv_data_box.iloc[index].loc['selected']]])
    #     last_name = csv_data_box.iloc[index].loc['sop']
    # with open('label_file/point.json', 'w') as f:
    #     json.dump(box_dict, f)

def save_pic(dcm_path,save_path):
    os.makedirs(save_path,exist_ok=True)
    for path, dir_list, file_list in tqdm(os.walk(dcm_path)):
        for file_name in file_list:
            try:
                dir = os.path.join(path, file_name)
                image,spacing = read_dcm_from_dir(dir)
                # print(spacing)
                image = monochrome_convert(image)
                cv2.imwrite(os.path.join(save_path,file_name.split('_')[1].replace('dcm','jpg')),image)
            except Exception as e:
                print(e)
                continue


def save_spacing(dcm_path):
    json_data = {}
    for path, dir_list, file_list in tqdm(os.walk(dcm_path)):
        for file_name in file_list:
            dir = os.path.join(path, file_name)
            image,spacing = read_dcm_from_dir(dir)
            json_data[file_name.split('_')[1].replace('dcm','')] = spacing
            print(spacing)
    with open('label_file/spacing.json', 'w') as f:
        json.dump(json_data,f)
        
    

def show_point(image_path,json_dir):
    json_data = json.load(open(json_dir))
    for anno in json_data:
        points = [p[0] for p in anno['point']]
        try:
            image = cv2.imread(os.path.join(image_path,anno['name']+'.jpg'))
            for point in points[24:25]:
                cv2.circle(image, (point[0],point[1]), 5, (255, 128, 255), thickness=30)
            cv2.imshow('image',cv2.resize(image,(512,512)))
            cv2.waitKey()
        except Exception as e:
            print(e)

def json_to_csv(json_dir,csv_dir):
    ## 将处理好关于点位的json转成csv文件
    json_file = json.load(open(json_dir))
    name_list = ['第1胸椎棘突','第2胸椎棘突','第3胸椎棘突','第4胸椎棘突','右侧第3肋骨外缘','右侧第4肋骨外缘',
                 '右侧第5肋骨外缘','右侧第6肋骨外缘','左侧第3肋骨外缘','左侧第4肋骨外缘','左侧第5肋骨外缘',
                 '左侧第6肋骨外缘','左侧锁骨内侧上缘','左侧锁骨内侧下缘','左侧锁骨外侧上缘','左侧锁骨外侧下缘',
                 '右侧锁骨内侧上缘','右侧锁骨内侧下缘','右侧锁骨外侧上缘','右侧锁骨外侧下缘','右侧肺尖','左侧肺尖',
                 '右侧肋膈角','左侧肋膈角','右侧心膈角','左侧心膈角']
    csv_data = pd.DataFrame(columns=['id']+name_list)
    for data in json_file:
        point = [p[0] for p in data['point']]
        point_dict = dict(zip(name_list,point))
        point_dict = {k:str(v) for k,v in point_dict.items()}
        point_dict['id'] = data['name']
        csv_data = csv_data.append(pd.DataFrame(point_dict,index=[0]))
    csv_data.to_csv(csv_dir,index=False)


def merge_data(file1,file2):
    ## 将两个csv文件进行合并，按照某一项数值
    data_1 = pd.read_csv(file1)
    data_2 = pd.read_excel(file2)
    merge_data = pd.merge(data_1,data_2,on='studyInstUid')
    merge_data.to_csv('label_file/merge.csv',index=False)

if __name__ == '__main__':
    # merge_data('label_file/point_csv.csv','label_file/score.xlsx')
    # json_to_csv(json_dir='label_file/point_0319.json',
    #             csv_dir='label_file/point_csv.csv')
    conver_csv(csv_dir='label_file\SRM_CHEST_DX_20210322.csv',
               save_json_dir='label_file/point_0322.json', )
    
    # show_point(image_path='/home/lmy/PycharmProjects/胸片异物/data/image',json_dir='label_file/point.json')
    # save_spacing(dcm_path='/home/lmy/PycharmProjects/Chest_point/data/Chest_DX')
    # save_pic(dcm_path='/home/lmy/PycharmProjects/Chest_point/data_0304/',
    #          save_path='data_0304/images')